package cn.itcast.shiro;

import cn.itcast.domain.Module;
import cn.itcast.domain.User;
import cn.itcast.service.module.ModuleService;
import cn.itcast.service.user.UserService;
import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class WxOpenIdRealm extends AuthorizingRealm {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ModuleService moduleService;
    @Autowired
    private UserService userService;

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("02执行到配置文件中:/system/module/list.do=perms['模块管理']会来该方法中查询登录用户的具备权限");

        //认证
        //方法参数：是安全数据的集合
        User user =(User)principals.getPrimaryPrincipal();
        System.out.println(user);
        List<Module> list = moduleService.findMenus(user);
        Set<String> set = new HashSet<>();
        for (Module module : list) {
            set.add(module.getName());
        }
        System.out.println("该认证用户具备的权限:"+set);
        //返回参数：是权限集合
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setStringPermissions(set);
        return simpleAuthorizationInfo; //没有任何权限
    }

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("进入了email 的  登录");
        String openid = (String) token.getCredentials();
        User user = userService.findByOpenId(openid);//根据传入的openId等查询数据库
        if (user == null) {
            logger.error(user.getUserName() + "-此openId未绑定");
            return null;
        }
        //return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
        return new SimpleAuthenticationInfo(user, null, null, this.getName());
    }
}
